package kamkor.webtoolseditor;


import kamkor.webtools.url.UrlParser;
import kamkor.webtools.url.UrlSwapper;
import kamkor.webtools.url.UrlTagger;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.extensions.ajax.markup.html.IndicatingAjaxButton;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.form.SimpleFormComponentLabel;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.Model;
import org.apache.wicket.validation.validator.PatternValidator;

/**
 * Editor form
 * 
 * @author kamkor
 *
 */
public class EditorForm extends Form {

	private static final long serialVersionUID = 1L;
	
	/** Example urls that will be inserted into TextArea model */
	private String exampleUrls = "Troche fotek:\n\n1\n[img]http://img109.imageshack.us/img109/4702/22164066.jpg[/img]\n" +
		"2\nhttp://img109.imageshack.us/img109/865/62727828.jpg\n" +
		"3\n[img]http://img109.imageshack.us/img109/7779/17567607.jpg[/img]\n" +
		"4\n[img]http://img14.imageshack.us/img14/4576/56896298.jpg[/img]\n" +
		"5\n[img]http://img14.imageshack.us/img14/6048/67719987.jpg[/img]\n" +
		"\nI troche nieistniejacych filmow: \n\n" +
		"http://www.driftingo.pl/media/download/film1.avi http://www.driftingo.pl/media/film.wmv\n\n" +
		"Oraz zdjec http://www.driftingo.pl/zdjecie.gif http://www.driftingo.pl/media/dorifto.png";
	
	/** Feedback displays errors to user */
	private FeedbackPanel feedback;
		
	/** Used in ajax buttons when adding to target */
	private TextArea editorTextArea;
	
	/** Used in ajax buttons when adding to target */
	private TextArea outputTextArea;		
	
	/** Model for editor TextArea */
	private Model<String> text = new Model<String>(exampleUrls);
	
	/** Model for output, ie. when urls are parsed, they will be displayed in output */
	private Model<String> output = new Model<String>("");
	
	/** Model for extensions input (TextField) */
	private Model<String> extensions = new Model("jpg png gif");
	
	/** Model for newUrl input (TextField) */
	private Model<String> newUrl = new Model<String>("http://www.driftforum.pl");
	
	/** Model for openTag input (TextField) */
	private Model<String> openTag = new Model<String>("[img]");
	
	/** Model for endTag input (TextField) */	
	private Model<String> closeTag = new Model<String>("[/img]");
	
	public EditorForm(String id, final FeedbackPanel feedback) {
		super(id);       		
		this.feedback = feedback;		

		FormComponent fc;
				
        // Editor text area
		// Save reference in editorTextArea for ajax use in buttons (target.add function)
		fc = editorTextArea = new TextArea<String>("text", text);	
    	fc.setOutputMarkupId(true);
    	add(fc);   	
    	
        // output text area for url parser
    	// Save reference in outputTextArea for ajax use in buttons (target.add function)
        fc = outputTextArea = new TextArea<String>("output", output);       
        fc.setOutputMarkupId(true);
        add(fc);
        
        // input for extensions   
        fc = new CustomAutoCompleteTextField("extensions", extensions, new String[] { "jpg", "png", "jpg png" });
    	fc.add(new PatternValidator("\\s*|(\\s*[\\w]+)+"));
    	fc.setLabel(new Model("extensions"));
    	add(fc);
    	add(new SimpleFormComponentLabel("extensionsLabel", fc));
    	
    	// input for new url 
    	fc = new TextField<String>("newUrl", newUrl);
    	fc.setLabel(new Model("new url"));      	
    	add(fc);
    	add(new SimpleFormComponentLabel("newUrlLabel", fc));    	
    	
    	// input for open tag, ie. [url]
    	fc = new CustomAutoCompleteTextField("openTag", openTag, new String[] { "[img]", "[url]", "[url=\"" });    	
    	fc.setLabel(new Model("tags"));
    	add(fc);
    	add(new SimpleFormComponentLabel("tagsLabel", fc));
    	
    	// input for end tag, ie. [/url]
    	fc = new CustomAutoCompleteTextField("closeTag", closeTag, new String[] { "[/img]", "[/url]", "\"][/url]" });     	      	
    	add(fc);  
    	
    	// Ajax buttons
    	add(new AddTagsButton("addTags", this));      	
    	add(new RemoveTagsButton("removeTags", this));
    	add(new ParseUrlsButton("parseUrls", this));        
    	add(new SwapHostButton("swapHost", this));
        add(new SwapHostAndPathButton("swapHostAndPath", this)); 
	}
	
	/**
	 * Replaces HostAndPath in urls
	 * 
	 * @author kamkor	
	 */
	private class SwapHostAndPathButton extends IndicatingAjaxButton {
		public SwapHostAndPathButton(String id, Form<?> form) {
			super(id, form);			
		}
		@Override
		protected void onSubmit(AjaxRequestTarget target, Form<?> arg1) {			
			if (target != null) {			
				String ext = extensions.getObject();					
				String replacementUrl = newUrl.getObject();	
									
				if (ext == null) {						
					text.setObject(UrlSwapper.replaceAllUrlPathIncluded(text.getObject(), replacementUrl));						
				} else {							
					text.setObject(UrlSwapper.replaceAllUrlPathIncluded(text.getObject(), replacementUrl, ext.split("\\s+")));						
				} 	
				target.addComponent(feedback);
				target.addComponent(editorTextArea);				
			}
		}
        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {
        	// repaint the feedback panel to show errors
        	target.addComponent(feedback);
        }
	}
	
	/**
	 * Replaces hosts in urls
	 * 
	 * @author kamkor
	 */
	private class SwapHostButton extends IndicatingAjaxButton {
		public SwapHostButton(String id, Form<?> form) {
			super(id, form);			
		}		
		@Override
		protected void onSubmit(AjaxRequestTarget target, Form<?> arg1) {			
			if (target != null) {
				
				String ext = extensions.getObject();					
				String replacementUrl = newUrl.getObject();	
				if (ext == null) {						
					text.setObject(UrlSwapper.replaceAllUrlHostOnly(text.getObject(), replacementUrl));
				} else {							
					text.setObject(UrlSwapper.replaceAllUrlHostOnly(text.getObject(), replacementUrl, ext.split("\\s+")));						
				} 	
				target.addComponent(feedback);
				target.addComponent(editorTextArea);
			}
		}
        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {
        	// repaint the feedback panel to show errors
        	target.addComponent(feedback);
        }
	}
	
	/**
	 * Button adds tags to urls
	 * 
	 * @author kamkor
	 *
	 */
	private class AddTagsButton extends IndicatingAjaxButton {			
		public AddTagsButton(String id, Form<?> form) {
			super(id, form);			
		}
		@Override
		protected void onSubmit(AjaxRequestTarget target, Form<?> arg1) {			
			if (target != null) {
				String ext = extensions.getObject();	
				String oTag = openTag.getObject();
				String eTag = closeTag.getObject();
				
				if(oTag != null && eTag != null) {
					if (ext == null) {					
						text.setObject(UrlTagger.addTags(text.getObject(), oTag, eTag));						
					} else { // extensions pattern is checked by validator, so else if is not needed							
						text.setObject(UrlTagger.addTags(text.getObject(), oTag, eTag, ext.split("\\s+")));						
					}					
				}			
				target.addComponent(feedback);
				target.addComponent(editorTextArea);
			}
		}		
        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {
        	// repaint the feedback panel to show errors
        	target.addComponent(feedback);
        }
	}
	
	/**
	 * Button removes tags from urls
	 * @author kamkor
	 *
	 */
	private class RemoveTagsButton extends IndicatingAjaxButton {
		public RemoveTagsButton(String id, Form<?> form) {
			super(id, form);			
		}

		@Override
		protected void onSubmit(AjaxRequestTarget target, Form<?> arg1) {
			String oTag = openTag.getObject();
			String cTag = closeTag.getObject();		
			
			if(target != null && oTag != null && cTag != null) {
				String ext = extensions.getObject();	
				
				if (ext == null) {						
					text.setObject(UrlTagger.removeTags(text.getObject(), oTag, cTag));					
				} else {							
					text.setObject(UrlTagger.removeTags(text.getObject(), oTag, cTag, ext.split("\\s+")));						
				}								
				target.addComponent(editorTextArea);
				target.addComponent(feedback);
			}
		}
        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {
        	// repaint the feedback panel to show errors
        	target.addComponent(feedback);
        }		
	}
	
	/**
	 * Parses urls from text and outputs them into outputTextArea
	 * @author kamkor
	 *
	 */
	private class ParseUrlsButton extends IndicatingAjaxButton {
		public ParseUrlsButton(String id, Form<?> form) {
			super(id, form);			
		}
		@Override
		protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
			if (target != null) {
				String ext = extensions.getObject();					
				String[] urls = null;
				if (ext == null) { // is empty					
					urls = UrlParser.parseUrlPathAndFileIncluded(text.getObject());						
				} else { // extensions pattern is checked by validator, so else if is not needed						
					urls = UrlParser.parseUrlPathAndFileIncluded(text.getObject(), ext.split("\\s+"));						
				}  		
				
				StringBuffer urlsBuffer = new StringBuffer();
				for(String url : urls) 
					urlsBuffer.append(url + "\n");				
				if (urlsBuffer.length() == 0)
					urlsBuffer.append("No urls found");
				
				output.setObject(urlsBuffer.toString());		
				
				target.addComponent(outputTextArea);			
				target.addComponent(editorTextArea);
				target.addComponent(feedback);
			}
		}		
        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {
        	// repaint the feedback panel so errors are shown
        	target.addComponent(feedback);
        }  
	}
}
